/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package it.polimi.deib.se2.meteocal.business.boundary;

import it.polimi.deib.se2.meteocal.business.entity.Location;
import java.security.Principal;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class LocationManager {
    
    @PersistenceContext
    EntityManager em;
    
    @Inject
    Principal principal;
    
    public void save(Location location) {
        em.persist(location);
    }
    
    public void update(Location location){
        em.merge(location);
    }
    
    public Location find(long id) {
        return em.find(Location.class, id);
    }
    
    public List<Location> getLocations() {
        Query q = em.createNativeQuery("SELECT * FROM meteocaldb.LOCATIONS;", Location.class);
        return q.getResultList();
    }
    
    public long isIn(String locationName) {
        try {
            return (Long) em.createNativeQuery("SELECT ID FROM LOCATIONS WHERE LOC_NAME=\""+locationName+"\"").getSingleResult();
        } catch (NoResultException e) {
            return 0;
        }
    }
    
    public void remove(Location location){
        em.remove(em.merge(location));
    }
}
